package leetcode.code2569;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.H;
import leetcode.templates.trees.segment.Node;

public class Solution_STNODE implements IDebug {

	public long[] handleQuery(int[] nums1, int[] nums2, int[][] queries) {
		List<Long> list = new ArrayList<>();
		long sum = 0;
		for (int num : nums2) {
			sum += num;
		}
		int n = nums1.length;
		Node o = new Node(0, n - 1);
		for (int i = 0; i < n; i++) {
			o.init(i, nums1[i]);
		}
		for (int[] query : queries) {
			int a = query[0], b = query[1], c = query[2];
			if (a == 1) {
				o.update(b, c);
			} else if (a == 2) {
				sum += 1l * o.cnt1 * b;// Long
			} else {
				list.add(sum);
			}
		}
		long[] ans = new long[list.size()];
		for (int i = 0; i < list.size(); i++) {
			ans[i] = list.get(i);
		}
		return ans;
	}

	class Node {
		private int L, M, R;

		private Node Left, Right;

		int cnt1;
		boolean update;

		public Node(int l, int r) {
			L = l;
			R = r;
			M = ((r - l) >> 1) + l;
		}

		public void reverse() {
			cnt1 = R - L + 1 - cnt1;
			update = !update;
		}

		public void update(int l, int r) {
			if (l == L && r == R) {
				reverse();
			} else {
				if (update) {
					left().reverse();
					right().reverse();
					update = !update;
				}
				if (l <= M) {
					left().update(l, Math.min(r, M));
				}
				if (M < r) {
					right().update(Math.max(l, M + 1), r);
				}
				cnt1 = left().cnt1 + right().cnt1;
			}
		}

		public void init(int x, int v) {
			if (L == R) {
				cnt1 = v;
			} else {
				if (x <= M) {
					left().init(x, v);
				} else {
					right().init(x, v);
				}
				cnt1 = left().cnt1 + right().cnt1;
			}
		}

		private Node left() {
			if (Left == null) {
				Left = new Node(L, M);
			}
			return Left;
		}

		private Node right() {
			if (Right == null) {
				Right = new Node(M + 1, R);
			}
			return Right;
		}

	}

	@Override
	public void debug4() {
		H.print(this.handleQuery(H.str2array3("[1,0,1]"), H.str2array3("[0,0,0]"),
				H.str2array1("[[1,1,1],[2,1,0],[3,0,0]]")));
		H.compare(H.str2array3("[539,1279,1279,1279]"), this.handleQuery(
				H.str2array3("[0,1,1,0,1,0,0,1,0,0,0,0,1,1,0,1,1,0,1]"),
				H.str2array3("[6,10,9,14,32,15,18,26,8,25,44,8,19,47,37,19,5,28,40]"), H.str2array1(
						"[[1,12,15],[1,13,18],[2,15,0],[1,11,15],[2,3,0],[1,3,11],[1,17,17],[3,0,0],[2,30,0],[2,6,0],[2,14,0],[1,7,14],[2,30,0],[3,0,0],[1,11,18],[3,0,0],[3,0,0]]")));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution_STNODE so = new Solution_STNODE();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
